package com.avic.rong.activity.mine;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avic.rong.BaseActivity;
import com.avic.rong.MainActivity;
import com.avic.rong.MyApplication;
import com.avic.rong.R;
import com.avic.rong.activity.IncreaseTQ.AuditSuccessActivity;
import com.avic.rong.activity.IncreaseTQ.Increase_TpActivity;
import com.avic.rong.activity.IncreaseTQ.NotThroughActivity;
import com.avic.rong.activity.IncreaseTQ.WaitAuditActivity;
import com.avic.rong.activity.interest.FocusAreaActivity;
import com.avic.rong.activity.login.LoginPhoneActivity;
import com.avic.rong.activity.product.OnlineCServiceActivity;
import com.avic.rong.api.ExitAccountApi;
import com.avic.rong.api.increase_tp.IncreaseTicketApi;
import com.avic.rong.api.mine.AccountSetApi;
import com.avic.rong.bean.CartListReloadEvent;
import com.avic.rong.bean.GoCartListEvent;
import com.avic.rong.bean.HomePageEvent;
import com.avic.rong.bean.MinePageEvent;
import com.avic.rong.bean.increase_tp.IncreaseTpBean;
import com.avic.rong.bean.mine.AccountSetBean;
import com.avic.rong.shoppingCar.activity.ShoppingCarActivity;
import com.avic.rong.userOrder.activity.AddressListActivity;
import com.avic.rong.utils.CleanMessageUtils;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.DeviceUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.utils.http.UpdateAppHttpUtil;
import com.avic.rong.wedgit.StringUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.example.minato.minastore.utils.AppUtils;
import com.luck.picture.lib.dialog.CustomDialog;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import com.vector.update_app.listener.ExceptionHandler;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

//账号设置
public class AccountSettingActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.rl_own_info)
    RelativeLayout rl_own_info;
    @BindView(R.id.rl_havvest_address)
    RelativeLayout rl_havvest_address;
    @BindView(R.id.rl_account_security)
    RelativeLayout rl_account_security;
    @BindView(R.id.rl_increase_tp)
    RelativeLayout rl_increase_tp;
    @BindView(R.id.rl_focus_area)
    RelativeLayout rl_focus_area;
    @BindView(R.id.tv_help_center)
    RelativeLayout tv_help_center;
    @BindView(R.id.rl_suggestion)
    RelativeLayout rl_suggestion;
    @BindView(R.id.rl_clean)
    RelativeLayout rl_clean;
    @BindView(R.id.rl_about)
    RelativeLayout rl_about;
    @BindView(R.id.tv_cache)
    TextView tv_cache;
    @BindView(R.id.btn_exit)
    Button btn_exit;
    @BindView(R.id.iv_user_head)
    ImageView iv_user_head;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_nickname)
    TextView tv_nickname;
    @BindView(R.id.tv_version)
    TextView tv_version;

    private PopupWindow popupWindow;
    private View popView;
    private String login_token;


    @BindView(R.id.tv_app_version)
    TextView tv_app_version;

    //全局定义
    private long lastClickTime = 0L;
    // 两次点击间隔不能少于1000ms
    private static final int FAST_CLICK_DELAY_TIME = 1000;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_account_setting;
    }


    @Override
    protected void initView() {
        tvTitle.setText("账号设置");
        ivRight.setBackgroundResource(R.mipmap.slh);

        /*if (!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }*/
        if (SharedPreferencesUtil.isLogin()) {
            login_token = SharedPreferencesUtil.getLoginToken();
        }

        try {
            String totalCacheSize = CleanMessageUtils.getTotalCacheSize(MyApplication.getInstance());
            tv_cache.setText(totalCacheSize);
        } catch (Exception e) {
            e.printStackTrace();
        }

        tv_app_version.setText("v" + DeviceUtils.getVersionName(AccountSettingActivity.this));


        AccountSetApi accountSetApi = new AccountSetApi(this, accountSetApiListener);
        accountSetApi.setArgument(login_token);
        accountSetApi.setCancel(false);
        accountSetApi.setShowProgress(true);
        HttpManager.getInstance().doHttpDeal(accountSetApi);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 100) {
            String logo = data.getStringExtra("logo");
            String name = data.getStringExtra("name");
            // Toast.makeText(getContext(), "logo"+logo+"       name:"+name, Toast.LENGTH_SHORT).show();
            if (!StringUtil.isEmpty(logo)) {
                RequestOptions requestOptions = new RequestOptions().error(R.mipmap.ic_default_head).circleCrop();
                Glide.with(this).applyDefaultRequestOptions(requestOptions).load(logo).into(iv_user_head);
            }
            tv_nickname.setText(name);
        }
    }

    @Override
    protected void addListener() {
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ivRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popView = LayoutInflater.from(AccountSettingActivity.this).inflate(R.layout.function_of_direct, null, false);
                commonPop(popView);
                initListener(AccountSettingActivity.this);
            }
        });
    }

    HttpOnNextListener<BaseResultEntity> accountSetApiListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                AccountSetBean data = (AccountSetBean) baseResultEntity.getData();
                tv_name.setText(data.getUserName());
                tv_nickname.setText(data.getNickName());
                String logo = data.getLogo();
                if (logo == null) {
                    String userPhoto = SharedPreferencesUtil.getInstance(AccountSettingActivity.this).getUserPhoto();
                    logo = userPhoto;
                }
                RequestOptions requestOptions = RequestOptions.circleCropTransform().error(R.mipmap.deafult_image_header);
                Glide.with(AccountSettingActivity.this).applyDefaultRequestOptions(requestOptions)
                        .load(logo).into(iv_user_head);
                String[] version = data.getVersion().split(" ");
//                tv_app_version.setText("当前版本"+version[1]);


            } else {
                Toast toast = Toast.makeText(AccountSettingActivity.this, baseResultEntity.getMsg(), Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }
        }
    };


    @OnClick({R.id.rl_own_info, R.id.rl_havvest_address, R.id.rl_account_security, R.id.rl_increase_tp, R.id.rl_focus_area, R.id.tv_help_center, R.id.rl_suggestion, R.id.rl_clean, R.id.rl_about, R.id.btn_exit, R.id.rl_app_version})
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.rl_own_info:
                if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
                    return;
                }
                lastClickTime = System.currentTimeMillis();
                startActivityForResult(OwnMessageActivity.queryIntent(AccountSettingActivity.this), 1);
                break;
            case R.id.rl_havvest_address:
                if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
                    return;
                }
                lastClickTime = System.currentTimeMillis();
                Intent intent = new Intent(context, AddressListActivity.class);
                intent.putExtra("enterType", "设置");
                startActivity(intent);
                break;
            case R.id.rl_account_security:
                if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
                    return;
                }
                lastClickTime = System.currentTimeMillis();
                startActivity(AccountSecurityActivity.queryIntent(AccountSettingActivity.this));
                break;
            case R.id.rl_increase_tp://增票资质信息
                increaseTp();
                break;
            case R.id.rl_focus_area:
                if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
                    return;
                }
                lastClickTime = System.currentTimeMillis();
                startActivity(FocusAreaActivity.queryIntent(AccountSettingActivity.this));
                break;
            case R.id.tv_help_center:
                if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
                    return;
                }
                lastClickTime = System.currentTimeMillis();
                startActivity(UserHelperCenterActivity.queryIntent(AccountSettingActivity.this, "123456"));
                break;
            case R.id.rl_suggestion://反馈意见
                if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
                    return;
                }
                lastClickTime = System.currentTimeMillis();
                startActivity(SuggestionActivity.queryIntent(AccountSettingActivity.this));
                break;
            case R.id.rl_clean:
                showDialog();
                break;
            case R.id.rl_about:
                if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
                    return;
                }
                lastClickTime = System.currentTimeMillis();
                startActivity(AboutActivity.queryIntent(AccountSettingActivity.this));
                break;
            case R.id.btn_exit:
                if (login_token != null) {
                    showDia();
                } else {
                    Toast toast = Toast.makeText(context, "用户还未登录", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                }
                break;
            case R.id.rl_app_version://当前版本
                if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
                    return;
                }
                lastClickTime = System.currentTimeMillis();

                apkUpdateSetUp();
                break;
        }
    }

    private void showDia() {
        CustomDialog customDialog = new CustomDialog(this, R.layout.dialog_exit);
        customDialog.show();
        customDialog.setCanceledOnTouchOutside(false);

        customDialog.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customDialog.cancel();
            }
        });
        customDialog.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                exit();
                customDialog.cancel();
            }
        });

    }

    private void apkUpdateSetUp() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("type", "0");
//        int versionCode = DeviceUtils.getVersionCode(AccountSettingActivity.this);
//        params.put("versionCode", String.valueOf(versionCode));

        new UpdateAppManager
                .Builder()
                //当前Activity
                .setActivity(this)
                //更新地址
                .setUpdateUrl(AppUtils.BASE_URL + AppUtils.URL_APK_UPDATE)
                .handleException(new ExceptionHandler() {
                    @Override
                    public void onException(Exception e) {
                        e.printStackTrace();
                    }
                })
                //实现httpManager接口的对象
                .setHttpManager(new UpdateAppHttpUtil())
                .setParams(params)
                .setPost(true)
                .setThemeColor(ContextCompat.getColor(AccountSettingActivity.this, R.color.update_theme_color))
                .setTopPic(R.mipmap.top_8)
                .build().checkNewApp(new CheckNewCallBack());
    }

    public class CheckNewCallBack extends UpdateCallback {
        @Override
        protected void noNewApp(String error) {
            ToastTools.showToast(AccountSettingActivity.this, error);
        }
    }

    private void increaseTp() {
        IncreaseTicketApi increaseTicketApi = new IncreaseTicketApi(this, auditSuccessListener);
        increaseTicketApi.setToken(login_token);

        HttpManager.getInstance().doHttpDeal(increaseTicketApi);
    }

    HttpOnNextListener<BaseResultEntity> auditSuccessListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                IncreaseTpBean data = (IncreaseTpBean) baseResultEntity.getData();
                if (data == null) {
                    startActivity(Increase_TpActivity.queryIntent(AccountSettingActivity.this));
                } else {
                    int status = data.getStatus();
                    if (status == 0) {
                        //显示待审核页面
                        startActivity(WaitAuditActivity.queryIntent(AccountSettingActivity.this));
                    } else if (status == 1) {
                        //显示审核通过
                        Intent intent = AuditSuccessActivity.queryIntent(AccountSettingActivity.this);
                        intent.putExtra("increaseSuccess", data);
                        startActivity(intent);
                    } else if (status == 2) {
                        //审核不通过
                        Intent intent = NotThroughActivity.queryIntent(AccountSettingActivity.this);
                        intent.putExtra("increaseFail", data);
                        startActivity(intent);

                    }
                }
            } else {
                Toast toast = Toast.makeText(AccountSettingActivity.this, baseResultEntity.getMsg() + "  " + baseResultEntity.getCode(), Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }
        }
    };

    private void exit() {
        ExitAccountApi exitAccountApi = new ExitAccountApi(this, exitAccountLstener);
        exitAccountApi.setArguments(login_token);
        HttpManager.getInstance().doHttpDeal(exitAccountApi);
    }

    HttpOnNextListener<BaseResultEntity> exitAccountLstener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                SharedPreferencesUtil.getInstance(AccountSettingActivity.this).clearUserInfo();//清空用户信息
                startActivity(LoginPhoneActivity.getIntent(AccountSettingActivity.this, "MinePageEvent"));
                finish();
            }
        }
    };


    private void showDialog() {

        CustomDialog alertDialog = new CustomDialog(this, R.layout.clean_dialog);
        alertDialog.show();
        alertDialog.setCanceledOnTouchOutside(false);

        alertDialog.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.cancel();
            }
        });
        alertDialog.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CleanMessageUtils.clearAllCache(AccountSettingActivity.this);
                tv_cache.setText("0.00KB");
                alertDialog.cancel();
            }
        });
    }

    private void initListener(Context context) {
        ImageView img_close_pop = popView.findViewById(R.id.img_close_pop);
        Button bt_home = popView.findViewById(R.id.bt_home);
        Button bt_mall = popView.findViewById(R.id.bt_mall);
        Button bt_news = popView.findViewById(R.id.bt_news);
        Button bt_own = popView.findViewById(R.id.bt_own);
        Button bt_goods_car = popView.findViewById(R.id.bt_goods_car);
        Button bt_kefu = popView.findViewById(R.id.bt_kefu);

        img_close_pop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        bt_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                EventBus.getDefault().postSticky(new HomePageEvent());
                startActivity(MainActivity.queryIntent(context));
            }
        });
        bt_mall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                EventBus.getDefault().postSticky(new GoCartListEvent());
                startActivity(MainActivity.queryIntent(context));
            }
        });
        bt_news.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                EventBus.getDefault().postSticky(new CartListReloadEvent());
                startActivity(MainActivity.queryIntent(context));
            }
        });
        bt_own.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                EventBus.getDefault().postSticky(new MinePageEvent());
                startActivity(MainActivity.queryIntent(context));
            }
        });
        bt_goods_car.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                startActivity(ShoppingCarActivity.queryIntent(context));
            }
        });
        bt_kefu.setOnClickListener(new View.OnClickListener() {//客服
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                startActivity(OnlineCServiceActivity.getIntent(context, "123456"));
            }
        });


    }

    private void commonPop(View view) {
        popupWindow = new PopupWindow(view, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
       /* // 产生背景变暗效果
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = 0.4f;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);*/
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.setClippingEnabled(false);
        //从上往下弹出动画效果
        popupWindow.setAnimationStyle(R.style.topPopupAnimation);
        popupWindow.showAtLocation(findViewById(R.id.ll_root), Gravity.TOP, 0, 0);
       /* popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            // 在dismiss中恢复透明度
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow()
                        .getAttributes();
                lp.alpha = 1f;
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                getWindow().setAttributes(lp);
            }
        });*/
    }

    public static Intent queryIntent(Context context) {
        Intent intent = new Intent(context, AccountSettingActivity.class);
        return intent;
    }
}
